package comment

import (
	"context"
	"gitee.com/enjoy_5/comment-rpc/constant"
	"gitee.com/enjoy_5/comment-rpc/proto/comment"
	"gitee.com/xuxinzhi2206/corehub/nacos"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

func client(_ context.Context, hand func(c comment.CommentClient) error) error {
	addr, err := nacos.FindHealthService(constant.ServiceName, constant.GroupName)
	if err != nil {
		return err
	}
	//建立一个GRPC的链接
	conn, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		return err
	}

	//延迟关闭链接
	defer conn.Close()

	//获取user client
	c := comment.NewCommentClient(conn)

	//将client 传递给闭包函数并执行闭包内的内容
	return hand(c)
}

func GetCommentList(ctx context.Context, in *comment.GetListReq) (info *comment.GetListResp, err error) {
	err = client(ctx, func(c comment.CommentClient) error {
		list, err := c.GetCommentList(ctx, in)
		if err != nil {
			return err
		}
		info = list
		return nil
	})
	return
}

func CreateComment(ctx context.Context, in *comment.CreateCommentReq) (info *comment.CreateCommentResp, err error) {
	err = client(ctx, func(c comment.CommentClient) error {
		_, err = c.AddComment(ctx, in)
		if err != nil {
			return err
		}

		return nil
	})
	return
}
func DelComment(ctx context.Context, in *comment.DelCommentReq) (info *comment.DelCommentResp, err error) {
	err = client(ctx, func(c comment.CommentClient) error {
		del, err := c.DelComment(ctx, in)
		if err != nil {
			return err
		}
		info = del
		return nil
	})
	return
}
func LikeComment(ctx context.Context, in *comment.UpdateLikeReq) (info *comment.UpdateLikeResp, err error) {
	err = client(ctx, func(c comment.CommentClient) error {
		_, err = c.UpdateLike(ctx, in)
		if err != nil {
			return err
		}
		return nil
	})
	return
}

func GetCNumByRat(ctx context.Context, in *comment.GetCNumByRatReq) (info *comment.GetCNumByRatResp, err error) {
	err = client(ctx, func(c comment.CommentClient) error {
		data, err := c.GetCNumByRat(ctx, in)
		if err != nil {
			return err
		}
		info = data
		return nil
	})
	return
}
